package com.opensource.afuluo.pipeline;

import com.alibaba.fastjson.JSON;
import com.opensource.afuluo.ctx.Context;
import com.opensource.afuluo.valve.Valve;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 默认管道流实现
 */
public class CommonPipeline implements Pipeline {

    private static final Logger log = LoggerFactory.getLogger(CommonPipeline.class);

    List<Valve> chain = new ArrayList<>();

    public CommonPipeline(String[] valves) {

    }

    public CommonPipeline(List<Valve> valves) {
        this.chain = valves;
    }

    @Override
    public Valve head() {
        if (CollectionUtils.isEmpty(chain)) {
            return null;
        }
        return chain.get(0);
    }

    @Override
    public Valve tail() {
        if (CollectionUtils.isEmpty(chain)) {
            return null;
        }
        return chain.get(chain.size() - 1);
    }

    @Override
    public int size() {
        return chain.size();
    }

    @Override
    public String toPlain() {
        // 应该自定义处理，先暂时用JSON将就一下
        return JSON.toJSONString(chain);
    }

    @Override
    public void entry(Context ctx) {
        if (size() > 0) {
            Iterator<Valve> valves = chain.iterator();
            while (!ctx.hasError()
                    && !ctx.isInterrupted()
                    && valves.hasNext()) {
                valves.next().offer(ctx);
            }
            if (ctx.hasError()) {
                tail().offer(ctx);
                log.error(ctx.getError());
            }
        }
    }
}
